<template>
  <div class="app-container">
    <el-form :inline="true" label-width="120px">
      <el-form-item label="活动创建时间">
        <el-date-picker
          v-model="timeValue"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动类目">
        <el-select v-model="queryParams.activityClassification" clearable>
          <el-option
            v-for="i in activityOptions"
            :key="i.createTime"
            :value="i.dictValue"
            :label="i.dictLabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动名称">
        <el-input
          placeholder="请输入活动名称"
          v-model="queryParams.activityName"
        ></el-input>
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="queryParams.status" clearable>
          <el-option
            v-for="i in statusLabel"
            :key="i.dictValue"
            :value="i.dictValue"
            :label="i.dictLabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="serachFn"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="list">
      <el-table-column type="index"></el-table-column>
      <el-table-column
        prop="activeCreateTime"
        label="活动创建时间"
      ></el-table-column>
      <el-table-column
        prop="userNickName"
        label="用户昵称"
      ></el-table-column>
      <el-table-column label="活动类目">
        <template slot-scope="scope">
          <span>{{ activityClassName(scope.row.activityClassification) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="activityName" label="活动名称"> </el-table-column>
      <el-table-column
        prop="declarationDescribe"
        label="申报描述"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="statusTag[scope.row.status]">
            {{
              scope.row.status == 0
                ? "待审核"
                : scope.row.status == 1
                ? "通过"
                : "驳回"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="rewardPoints" label="申报积分"> </el-table-column>
      <el-table-column prop="rejectReason" label="备注">
        <template slot-scope="scope" v-if="scope.row.status == 2">
          <span>驳回理由：{{ scope.row.rejectReason }}</span></template
        >
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            >附件查看</el-button
          >
          <el-button
            v-if="scope.row.status == 2"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleEmit(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      :page.sync="queryParams.params.pageNum"
      :limit.sync="queryParams.params.pageSize"
      @pagination="getList"
    />
    <el-dialog title="附件信息" :visible.sync="dialogDetail" width="500px">
      <ul class="file-list-dialog">
        <li v-for="(file, index) in processDetail" :key="index">
          <div class="file-name">
            <i class="el-icon-s-order" />{{ file.name }}
          </div>
          <div class="file-tag">
            <el-button
              type="success"
              size="mini"
              :loading="file.loadingBtn"
              @click="preview(file)"
              >预览</el-button
            >
            <el-button type="primary" size="mini" @click="downloadFn(file)"
              >下载</el-button
            >
          </div>
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogDetail = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="活动资料信息修改"
      :visible.sync="dialogHandleProcess"
      width="800px"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="活动名称" :label-width="formLabelWidth">
          <el-input
            v-model="form.activityName"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="活动类目" :label-width="formLabelWidth">
          <el-input
            autocomplete="off"
            v-model="form.activityClassification"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="活动时间" :label-width="formLabelWidth" prop="activeJoinTime">
            <el-date-picker
            value-format="yyyy-MM-dd"
        v-model="form.activeJoinTime"
        type="date"
        placeholder="选择活动时间">
      </el-date-picker>
        </el-form-item>
        <el-form-item
          label="申报描述"
          :label-width="formLabelWidth"
          prop="declarationDescribe"
        >
          <el-input
            v-model="form.declarationDescribe"
            autocomplete="off"
            type="textarea"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="申报附件"
          :label-width="formLabelWidth"
          prop="fileList"
        >
          <FileUpload
            ref="child"
            :fileType="fileType"
            :fileSize="20"
            :value="fileListData"
            :limit="10"
            @input="fileList"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogHandleProcess = false">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { listData } from "@/api/system/dict/data";
import { integralDetailApi,integralApplyApi ,integralPreviewApi} from "@/api/party/integral";
export default {
  data() {
    var checkFile = (rule, value, callback) => {
      if (!this.form.filePath) {
        return callback(new Error("请上传申报附件！"));
      }
      callback();
    };
    return {
      fileListData:[],
      fileType: [
        "doc",
        "docx",
        "xls",
        "xlsx",
        "ppt",
        "pptx",
        "pdf",
        "jpg",
        "jpeg",
        "png",
      ],
      rules: {
        declarationDescribe: [
          { required: true, message: "请输入申报描述", trigger: "blur" },
        ],
        fileList: [{ required: true, validator: checkFile, trigger: "blur" }],
        activeJoinTime: [{ required: true, message: "请选择参加活动具体时间",  trigger: "blur" }],
      },
      formLabelWidth: "120px",
      dialogHandleProcess:false,
      form: {
        activityCode: "",
        activityName: "",
        declarationDescribe: "",
        activityClassification: "",
        activeJoinTime:null
      },
      dialogDetail: false,
      processDetail: null,
      statusTag: {
        0: "warning",
        1: "success",
        2: "danger",
      },
      activityOptions: [],
      loading: false,
      list: [],
      total: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      timeValue: "",
      //审核状态（0待审核 1通过 2驳回）
      statusLabel: [
        {
          dictLabel: "待审核",
          dictValue: "0",
        },
        {
          dictLabel: "通过",
          dictValue: "1",
        },
        {
          dictLabel: "拒绝",
          dictValue: "2",
        },
      ],
      queryParams: {
        activityClassification: null,
        activityName: "",
        status: "",
        params: {
          startTime: "",
          endTime: "",
          pageNum: 1,
          pageSize: 10,
        },
      },
    };
  },
  watch: {
    timeValue(e) {
      this.queryParams.params.startTime = e[0];
      this.queryParams.params.endTime = e[1];
    },
  },
  computed: {
    activityClassName() {
      return (activityClassification) => {
        let dictLabel = "";
        if (this.activityOptions.length == 0) return "";
        this.activityOptions.forEach((item) => {
          if (item.dictValue == activityClassification) {
            dictLabel = item.dictLabel;
          }
        });
        return dictLabel;
      };
    },
  },
  async created() {
    await this.listDataFn();
    await this.getList();
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          integralApplyApi(this.form).then((res) => {
            this.$modal.msgSuccess("重新提交申报成功");
            this.handleClose();
            this.getList()
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    fileList(list) {
      let fileNames = list
        .map((item) => this.getFileName(item.name))
        .toString();
      let filePath = list.map((item) => item.url).toString();
      this.$set(this.form, "fileNames", fileNames);
      this.$set(this.form, "filePath", filePath);
    },
       // 获取文件名称
       getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name||"";
      }
    },
    getActivityClassName(val) {
      let dictLabel = "";
      if (this.activityOptions.length == 0) return dictLabel;
      this.activityOptions.forEach((item) => {
        if (item.dictValue == val) {
          dictLabel = item.dictLabel;
        }
      });
      return dictLabel;
    },
    handleClose() {
      this.$refs.child.restList();
      this.form = {
        activityCode: "",
        activityName: "",
        declarationDescribe: "",
        activityClassification: "",
        activeJoinTime: null,
      };
      this.dialogHandleProcess = false;
    },
    handleEmit(e){
      this.$set(this.form, "activityName", e.activityName);
      this.$set(this.form, "activityCode", e.activityCode);
      this.$set(this.form, "declarationDescribe",e.declarationDescribe);
      this.$set(this.form, "activeJoinTime",e.activeJoinTime);
      this.fileListData=this.formatFile(e);
      console.log('🚀🚀',e);
      this.$set(
        this.form,
        "activityClassification",
        this.getActivityClassName(e.activityClassification)
      );
      this.dialogHandleProcess = true;
    },
    //附件格式化
    formatFile(v){
      let name, url;
      if (v.fileNames.indexOf(",") > 0) {
        name = v.fileNames.split(",");
      } else {
        name = [v.fileNames];
      }
      if (v.filePath.indexOf(",") > 0) {
        url = v.filePath.split(",");
      } else {
        url = [v.filePath];
      }
      let arr = [];
      name.forEach((item, index) => {
        arr.push({
          name: item,
          url: url[index],
          loadingBtn: false,
        });
      });
      return arr
    },
    //查看附件
    handleDetail(v) {
      if (!v.fileNames) {
        return this.$message({
          message: "该申报没有附件信息！",
          type: "warning",
        });
      }
      this.processDetail = this.formatFile(v);
      this.dialogDetail = true;
    },
    preview(file) {
      file.loadingBtn = true;
      //白名单
      let fileType = ["jepg", "jpg", "png", "map4", "pdf"];
      let suffix = file.name.split(".")[1];
      if (fileType.includes(suffix)) {
        file.loadingBtn = false;
        window.open(process.env.VUE_APP_BASE_API + file.url, "_blank");
      } else {
        integralPreviewApi(file.url).then((res) => {
          let blob = new Blob([res], { type: "application/pdf" });
          let url = window.URL.createObjectURL(blob);
          file.loadingBtn = false;
          window.open(url, "_blank");
        });
      }
    },
    downloadFn(row) {
      var name = row.name.split(".")[0];
      var url = process.env.VUE_APP_BASE_API + row.url;
      var suffix = url.substring(url.lastIndexOf("."), url.length);
      const a = document.createElement("a");
      a.setAttribute("download", name + suffix);
      a.setAttribute("target", "_blank");
      a.setAttribute("href", url);
      a.click();
    },
    //获取活动分类
    listDataFn() {
      listData({
        dictType: "activity_classification",
      }).then((res) => {
        this.activityOptions = res.rows;
      });
    },
    getList() {
      this.loading = true;
      integralDetailApi(this.queryParams)
        .then((res) => {
          this.total = res.total;
          this.list = res.rows;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    serachFn() {
      this.queryParams.params.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        activityClassification: null,
        activityName: "",
        status: "",
        params: {
          startTime: "",
          endTime: "",
          pageNum: 1,
          pageSize: 10,
        },
      };
      this.timeValue = "";
      this.getList();
    },
  },
};
</script>
<style scoped lang="scss">
.file-list-dialog {
  padding: 0;
  li {
    display: flex;
    margin-bottom: 10px;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    .file-name {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .file-tag {
      width: 150px;
      text-align: center;
      .el-tag {
        margin-left: 10px;
      }
    }
  }
}
::v-deep .el-textarea .el-input__count{
  bottom: -20px!important;
}
</style>